<template>
  <el-dialog
    :visible.sync="dialogVisible"
    :before-close="handleClose"
    :append-to-body="false"
    :show-close="false"
    :class="{'mobile-el-dialog': showMobilePage}"
    class="small-common-dialog-size create-Income-kind-dialog"
    @close="closeDialog"
    @opened="opened">
    <Title :title="!kindId?'添加收入项':'编辑收入项'" font-size="16px" style="margin-bottom:20px;"/>
    <el-form
      ref="configKindForm"
      :rules="rules"
      :model="queryData"
      :label-position="showMobilePage?'left':'right'"
      label-width="86px"
      class="setting-form lineHeight32">
      <el-form-item label="收入来源" prop="sourceId" style="margin-bottom: 24px;">
        <el-select v-model="queryData.sourceId" popper-class="global-select-down" class="width240" @change="sourceChange">
          <el-option label="请选择" value="" />
          <el-option
            v-for="item in sources"
            :key="item.value"
            :label="item.label"
            :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="收入项" prop="name" style="margin-bottom: 24px;">
        <el-input
          v-model.trim="queryData.name"
          type="text"
          size="small"
          maxlength="20"
          placeholder="最多20个字符"
        />
      </el-form-item>
      <el-form-item v-if="queryData.sourceId === 2" :show-message="false" prop="incomeDetail" style="margin: 0">
        <template slot="label">
          <div class="flex-center">
            <span style="color: #f56c6c;margin-right:4px;">*</span>
            <span class="label">收入细项</span>
          </div>
        </template>
        <incomeDetail
          ref="incomeDetail"
          :income-detail-list="incomeDetailList"
          class="income-content"
          @addItem="addItem()"
          @toDelete="toDelete($event)"
        />
      </el-form-item>
      <div v-if="queryData.sourceId === 2" class="btn" @click="addItem()">添加</div>
    </el-form>
    <div class="btn-container">
      <el-button :loading="loading" type="primary" size="small" @click="handleOk">确定</el-button>
      <el-button class="cancel-btn-style" size="small" style="width: 80px" @click="handleClose">取消</el-button>
    </div>
  </el-dialog>
</template>
<script>
import Title from '@/components/Title';
import incomeDetail from './incomeDetail';
import { incomeKindEdit, incomeKindCreate } from '@/api/config';
import { mapState } from 'vuex';
import { generateUUID } from '@/utils/tools';
export default {
  name: 'CreateIncomeDialog',
  components: { Title, incomeDetail },
  data() {
    const validateName = (msg, key) => {
      return (rule, value, callback) => {
        const costType = this.queryData[key];
        if (!costType && costType !== 0) { callback(new Error(msg)); } else { callback(); }
      };
    };
    return {
      kindId: null,
      dialogVisible: false,
      antiShakeTime: 0,
      queryData: {
        name: '',
        sourceId: ''
      },
      incomeDetailList: [
      ],
      rules: {
        name: [{ required: true, trigger: 'blur', validator: validateName('请输入收入项', 'name') }],
        sourceId: [{ required: true, trigger: 'change', message: '请选择收入来源' }]
      },
      sources: [{
        value: 2,
        label: '商务订单'
      }, {
        value: 0,
        label: '渠道订单'
      }, {
        value: 1,
        label: '项目订单'
      }],
      loading: false
    };
  },
  computed: {
    ...mapState({
      'showMobilePage': state => state.app.showMobilePage
    })
  },
  methods: {
    initInfo(data) {
      if (data) {
        this.queryData.name = data.name;
        this.queryData.sourceId = data.sourceId;
        this.kindId = data.id;
        if (data.incomeDetail) {
          data.incomeDetail.split(',').forEach(el => {
            this.incomeDetailList.push({
              value: el
            });
          });
        } else {
          data.sourceId === 2 && this.addItem();
        }
      }
    },
    handleClose() {
      this.dialogVisible = false;
    },
    closeDialog() {
      this.queryData = {
        name: '',
        sourceId: ''
      };
      this.incomeDetailList = [
      ];
      if (Number(this.queryData.sourceId) === 2) {
        this.$refs.incomeDetail.clearError();
      }
      this.kindId = null;
      this.$refs.configKindForm.resetFields();
    },
    // 收入来源变更
    sourceChange(val) {
      if (val === 2 && !this.incomeDetailList.length) { // 萌力订单
        this.addItem();
      }
    },
    handleOk() {
      var timestamp = Date.parse(new Date());
      if (timestamp - this.antiShakeTime < 500) {
        return;
      }
      this.antiShakeTime = timestamp;
      this.$refs.configKindForm.validate(vaild => {
        const vaildIncomeDetail = Number(this.queryData.sourceId) === 2 ? this.$refs['incomeDetail'].validate() : true;
        if (vaild && vaildIncomeDetail) {
          const data = {
            ...this.queryData
          };
          if (Number(this.queryData.sourceId) === 2) {
            data.incomeDetailList = this.incomeDetailList;
            data.incomeDetailList.map((el, index) => {
              el.num = index;
            });
          }
          if (this.kindId || this.kindId === 0) {
            this.toEdit(data);
          } else {
            this.toAdd(data);
          }
        } else {
          return false;
        }
      });
    },
    addItem() {
      this.incomeDetailList.push({
        value: '',
        _uuid: generateUUID(),
        autofocus: true
      });
    },
    toDelete(index) {
      this.incomeDetailList.splice(index, 1);
    },
    opened() {
      // this.getIncomeSources();
    },
    toEdit(data) {
      this.loading = true;
      incomeKindEdit(this.kindId, data).then(res => {
        if (res.code === 200) {
          this.$message.success('修改成功');
          this.$emit('update', false);
          this.loading = false;
          this.dialogVisible = false;
        }
      }).catch((err) => {
        this.loading = false;
        if (err.code !== 500) {
          this.dialogVisible = false;
        }
      });
    },
    toAdd(data) {
      this.loading = true;
      incomeKindCreate(data).then(res => {
        if (res.code === 200) {
          this.$message.success('添加成功');
          this.$emit('update');
          this.loading = false;
          this.dialogVisible = false;
        }
      }).catch((err) => {
        this.loading = false;
        if (err.code !== 500) {
          this.dialogVisible = false;
        }
      });
    }
  }
};
</script>
<style lang="scss" scoped>
.btn-container {
  display: flex;
  justify-content: center;
}
.create-Income-kind-dialog {
  &::v-deep {
    .el-dialog{
      max-height: 80vh !important;
      width: 430px !important;
    }
    .el-input {
      .el-input__inner {
        height: 32px !important;
        width: 240px;
      }
      .el-select__caret {
        line-height: 32px;
      }
    }
  }
  .btn{
    cursor: pointer;
    white-space: nowrap;
    color: #406EFF;
    margin:0 0 22px 86px;
  }
  .income-content{
    max-height: 33vh !important;
    overflow: auto;
  }
}
.mobile-el-dialog {
  &::v-deep {
    .el-dialog{
      width: 100% !important;
    }
  }
}
</style>
